package com.hurui.xiaoming.activity.me;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnDrawListener;
import com.github.barteksc.pdfviewer.listener.OnErrorListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageScrollListener;
import com.hurui.xiaoming.R;
import com.hurui.xiaoming.activity.BaseActivity;
import com.hurui.xiaoming.bean.Li_ContractResult;
import com.hurui.xiaoming.bean.Li_MakeContractResult;
import com.hurui.xiaoming.utils.BitmapUtils;
import com.hurui.xiaoming.utils.DefultData;
import com.hurui.xiaoming.utils.ProgressDialog;
import com.hurui.xiaoming.utils.WriteReadSharedPrefs;
import com.hurui.xiaoming.weight.PaintView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ContractInfoActivity extends BaseActivity {

    Intent intent;
    Li_ContractResult.DataBean dataBean;
    String type;

    private ImageView back_iv;
    private TextView title_tv;
    public Button commit;
    Map map = new HashMap();

    //private WebView mWebView;
    private String pdfUrl;
    ProgressDialog dialog;

    private Bitmap baseBitmap;
    //private Canvas canvas = new Canvas();
    private Canvas canvas;
    private Paint paint;
    RelativeLayout bitmapLayout;
    PaintView backView;

    private PDFView pdfView ;
    private TextView tijiao;
    private TextView quxiao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contract_info);

        intent = getIntent();

        initView();
        initAction();
        getNetData();
    }

    @Override
    public void initView() {
        dataBean = (Li_ContractResult.DataBean) intent.getSerializableExtra("databean");
        type = intent.getStringExtra("contract");


        if("1".equals(type)){
            pdfUrl = dataBean.getOi_pdf1();
        }else if("2".equals(type)){
            pdfUrl = dataBean.getOi_pdf2();
        }else if("3".equals(type)){
            pdfUrl = dataBean.getOi_pdf3();
        }
        back_iv = (ImageView) findViewById(R.id.back_iv);
        title_tv = (TextView) findViewById(R.id.top_title_tv);
        title_tv.setText("合同详情");

        commit = (Button) findViewById(R.id.commit);

        dialog = new ProgressDialog(this);
        dialog.showDialog("请稍后...");

        pdfView = (PDFView) findViewById( R.id.pdfView );

        bitmapLayout = (RelativeLayout) findViewById(R.id.bitmapLayout);
        backView = ((PaintView) findViewById(R.id.backView));
        tijiao = (TextView) findViewById(R.id.tijiao);
        quxiao = (TextView) findViewById(R.id.cancle);
    }

    @Override
    public void initAction() {
        back_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onFinish();
            }
        });

        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if("9".equals(WriteReadSharedPrefs.readUserUI_Type(mContext))){
                    getData();
                }else{
                    //弹出签字蒙板
                    bitmapLayout.setVisibility(View.VISIBLE);
                }
            }
        });

        tijiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.showDialog("请稍等...");
                getData();
                //saveCustomViewBitmap();
            }
        });

        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                backView.removeAllPaint();
                bitmapLayout.setVisibility(View.GONE);

            }
        });
    }

    public void showPdf(InputStream stream ){


        pdfView.fromStream(stream)
//.pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
                .enableSwipe(true)
                .swipeHorizontal(false)
                .enableDoubletap(true)
                .defaultPage(0)
                .onDraw(new OnDrawListener() {
                    @Override
                    public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {

                    }
                })
                .onLoad(new OnLoadCompleteListener() {
                    @Override
                    public void loadComplete(int nbPages) {
                        dialog.cancelDialog();
                        //Toast.makeText(getApplicationContext(), "loadComplete", Toast.LENGTH_SHORT).show();
                    }
                })
                .onPageChange(new OnPageChangeListener() {
                    @Override
                    public void onPageChanged(int page, int pageCount) {

                    }
                })
                .onPageScroll(new OnPageScrollListener() {
                    @Override
                    public void onPageScrolled(int page, float positionOffset) {

                    }
                })
                .onError(new OnErrorListener() {
                    @Override
                    public void onError(Throwable t) {
                        Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
                    }
                })
                .enableAnnotationRendering(true)
                .password(null)
                .scrollHandle(null)
                .load();
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1){
                case 0:
                    InputStream is = null;
                    try {
                        is = connection.getInputStream();
                        showPdf(is);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    break;
            }
        }
    };

    HttpURLConnection connection;
    public void getNetData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                try {
                    url = new URL(pdfUrl);
                    connection = (HttpURLConnection)
                            url.openConnection();
                    connection.setRequestMethod("POST");//试过POST 可能报错
                    connection.setDoInput(true);
                    connection.setConnectTimeout(10000);
                    connection.setReadTimeout(10000);
                    //实现连接
                    connection.connect();

                    if (connection.getResponseCode() == 200) {

                        //这里给过去就行了

                        Message msg = new Message();
                        msg.arg1 = 0;
                        handler.sendMessage(msg);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }).start();
    }

    /**
     * 获取网络数据
     */
    public void getData() {

        // 保存绘图为本地图片


        map.clear();
        map.put("oi_id", dataBean.getOi_id());
        map.put("hetong", type);
        map.put("ui_type",WriteReadSharedPrefs.readUserUI_Type(mContext));
        map.put("ui_id",WriteReadSharedPrefs.readUserID(mContext));
        map.put("ui_eqb_img", BitmapUtils.Bitmap2StrByBase64(backView.saveBitmap()));
        if (backView.saveBitmap() != null) {

            Log.i("测试数据", BitmapUtils.Bitmap2StrByBase64(backView.saveBitmap()));
            Call<Li_MakeContractResult> call = apiSevice.onHttpPostMakeContract(DefultData.makeContract, map);
            call.enqueue(new Callback<Li_MakeContractResult>() {
                @Override
                public void onResponse(Call<Li_MakeContractResult> call, Response<Li_MakeContractResult> response) {
                    Li_MakeContractResult li_makeContractResult = null;
                    if (response.isSuccessful()) {
                        li_makeContractResult = response.body();
                        if ("success".equals(li_makeContractResult.getStatus())) {
                            dialog.cancelDialog();
                            onToast("签名成功");
                            finish();
                        } else if ("false".equals(li_makeContractResult.getStatus())) {
                            onToast("失败");
                        } else {
                            onToast("未知错误");

                        }

                    } else {
                        onToast("获取合同列表失败");
                    }
                }

                @Override
                public void onFailure(Call<Li_MakeContractResult> call, Throwable t) {
                    onHttpFail(-1, t.getMessage());
                }
            });
        }
    }

}
